<template>
  <a-modal :visible="true" title="订单" :width="800" :footer="null" @cancel="cancel">
    <div class="model-box">
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 23 }"
        autocomplete="off"
        @finish="submit"
      >
        <a-form-item
          label="订单编号"
          name="OrderNum"
          :rules="[{ required: true, message: '请输入订单编号' }]"
        >
          <a-input v-model:value="formState.OrderNum" />
        </a-form-item>
        <a-form-item
          label="订单名称"
          name="OrderName"
          :rules="[{ required: true, message: '请输入订单名称' }]"
        >
          <a-input v-model:value="formState.OrderName" />
        </a-form-item>
        <a-form-item
          label="订单总金额"
          name="OrderPriceCount"
          :rules="[{ required: true, message: '请输入订单总金额' }]"
        >
          <a-input-number disabled style="width: 100%" v-model:value="formState.OrderPriceCount" />
        </a-form-item>
        <a-form-item
          label="订单负责人"
          name="OrderManager"
          :rules="[{ required: true, message: '请输入订单负责人' }]"
        >
          <a-input disabled v-model:value="data.userName" />
        </a-form-item>
        <div class="btn-box">
          <SelectGoods style="margin-right: 20px" @submit="addGoods" />
          <SelectUser
            class="select-box"
            :selectedIds="[data.userID]"
            :multiple="false"
            @change="getRuleUserIds"
            @changeNames="getRuleUserNames"
          >
            <a-button type="primary"> 选择负责人 </a-button>
          </SelectUser>
        </div>
        <a-table
          bordered
          :data-source="dataSource"
          :columns="columns"
          :pagination="{
            hideOnSinglePage: true,
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'ProductAmount'">
              <div class="editable-cell">
                <a-input-number v-model:value="record.ProductAmount" @change="save(record)" />
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除?"
                @confirm="onDelete(record.ProductID)"
              >
                <a>删除</a>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="margin: 10px 0">提交</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import type { PropType, Ref } from 'vue';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import SelectGoods from './SelectGoods.vue';
  import { add, edit } from './api/index';
  import { notification } from 'ant-design-vue';
  const emits = defineEmits(['cancel']);
  const props = defineProps({
    data: {
      type: Object as PropType<any>,
    },
  });
  const data = reactive({ key: '', userID: '', userName: '', OrderID: '' });
  const formState = reactive({
    OrderNum: '',
    OrderName: '',
    OrderManager: '',
    OrderPriceCount: 0,
  });
  interface DataItem {
    ProductID: string;
    key: string;
    ProductName: string;
    ProductUnitPrice: number;
    ProductAmount: number;
    ProductPriceCount: number;
  }
  const dataSource: Ref<DataItem[]> = ref([]);
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'ProductName',
    },
    {
      title: '单价',
      dataIndex: 'ProductUnitPrice',
    },
    {
      title: '数量',
      dataIndex: 'ProductAmount',
    },
    {
      title: '合计',
      dataIndex: 'ProductPriceCount',
    },
    {
      title: '操作',
      dataIndex: 'operation',
    },
  ];
  onMounted(() => {
    if (props.data.OrderID) {
      data.OrderID = props.data.OrderID;
      formState.OrderName = props.data.OrderName;
      formState.OrderNum = props.data.OrderNum;
      formState.OrderManager = props.data.OrderManager;
      data.userID = formState.OrderManager;
      data.userName = props.data.OrderManagerName;
      formState.OrderPriceCount = props.data.OrderPriceCount;
      if (props.data.OrderProduct.length > 0) {
        dataSource.value = props.data.OrderProduct;
      }
    }
  });
  const save = (item: DataItem) => {
    item.ProductPriceCount = item.ProductAmount * item.ProductUnitPrice;
    changeOrderPriceCount();
  };
  const onDelete = (key: string) => {
    dataSource.value = dataSource.value.filter((item) => item.ProductID !== key);
    changeOrderPriceCount();
  };
  function changeOrderPriceCount() {
    if (dataSource.value.length > 0) {
      formState.OrderPriceCount = dataSource.value.reduce(function (a, b) {
        return a + b.ProductPriceCount;
      }, 0);
    } else {
      formState.OrderPriceCount = 0;
    }
  }
  function getRuleUserIds(val) {
    data.userID = val[0];
    formState.OrderManager = val[0];
  }
  function getRuleUserNames(val) {
    data.userName = val;
  }
  function addGoods(list) {
    let demo = list.map((ele) => {
      ele['ProductPriceCount'] = 0;
      ele['ProductAmount'] = 0;
      return ele;
    });
    dataSource.value.push(...demo);
  }
  async function submit() {
    let res = false;
    if (data.OrderID) {
      let params = {
        ...formState,
        OrderID: data.OrderID,
        OrderProduct: dataSource.value,
      };
      try {
        res = await edit(params);
      } catch (error) {}
    } else {
      let params = {
        ...formState,
        OrderProduct: dataSource.value,
      };
      try {
        res = await add(params);
      } catch (error) {}
    }

    if (res) {
      notification.success({
        message: '提示',
        description: '添加成功',
      }); //提示消息
      cancel();
    } else {
      notification.error({
        message: '提示',
        description: '添加失败',
      }); //提示消息
    }
  }
  function cancel() {
    emits('cancel');
  }
</script>

<style scoped>
  .model-box {
    padding: 20px 30px;
  }

  .btn-box {
    display: flex;
    margin: 10px 0;
  }
</style>
